#! /bin/bash

# usage:
# gitlab-mr <project> <source_branch> [dev|fat]
# 在 project 项目创建一个source_branch到dev或fat的合并请求，然后执行合并（如果有权限）

function check_dst_branch()
{
    if test ! "$1" = 'dev' && test ! "$1" = 'fat' && test ! "$1" = 'snapshot'; then
        echo "only dev/fat dest branch allowed"
        exit 1
    fi
}

. gitlab-common.sh
read_project_from_yaml $1 # got $PROJECT_ID

BRANCH_SRC=$2
BRANCH_DST=$3

check_dst_branch $BRANCH_DST
if test $? -eq 1; then 
    exit 1
fi

# create merge request
TITLE="Merge from $BRANCH_SRC to $BRANCH_DST -- `date +'%F %R'`"
mr=`gitlab_exec create_merge_request $PROJECT_ID "${TITLE}" "{source_branch: '$BRANCH_SRC', target_branch: '$BRANCH_DST'}" --json`

web_url=`echo "$mr" | jq '.result.web_url'`
has_conflicts=`echo "$mr" | jq '.result.has_conflicts'`
mr_id=`echo "$mr" | jq '.result.iid'`
echo "Created merge request: $web_url"

if test "$has_conflicts" = 'true'; then
    echo "Conflicts detected, cancel merge"
    exit 1
fi

# changes=`gitlab_exec merge_request_changes $PROJECT_ID $mr_id --json`
changes=`gitlab_exec merge_request_changes $PROJECT_ID $mr_id --json | jq '.result.changes_count'`
if test "$changes" = '0' || test "$changes" = 'null'; then
    echo "No changes, cancel merge"
    exit 1
fi

echo "----Merge Result----"
gitlab_exec accept_merge_request $PROJECT_ID $mr_id --json
